package DB_file;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import relation.*;

import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Map;

/**
 *用于读取json文件
 * @author cgl-22341129
 */
public class JsonReader {

    private String charsetName;
    private String filepath;

    /**
     * 修改编码标准
     * @param charsetName 编码标准
     */
    public void setCharsetName(String charsetName) {
        this.charsetName = charsetName;
    }

    /**
     * 修改读取的路径
     * @param filepath 文件路径
     */
    public void setFilepath(String filepath) {
        this.filepath = filepath;
    }

    /**
     * 默认为UTF8
     * @param filepath
     */
    public JsonReader(String filepath) {
        this.charsetName = "UTF-8";
        this.filepath = filepath;
    }

    public JsonReader(String charsetName, String filepath) {
        this.charsetName = charsetName;
        this.filepath = filepath;
    }

    /**
     * 读取器，将json文件，读取为json类
     * @return 读取的json类
     */
    private JSONObject read(){
        File file=new File(filepath);
        if(!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println("创建文件失败");
                throw new RuntimeException(e);
            }
        }
        FileInputStream fileInputStream= null;
        try {

            fileInputStream = new FileInputStream(file);
            InputStreamReader reader=new InputStreamReader(fileInputStream,"UTF-8");
            StringBuffer buffer=new StringBuffer();
            while(reader.ready()){
                buffer.append((char)reader.read());
            }
            //System.out.println(buffer.toString());
            reader.close();
            fileInputStream.close();
            return JSON.parseObject(buffer.toString(), JSONObject.class);

        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 将读取到的json类转化为Table类
     * @return Table类
     */
    public Table readtable(){
       return Table.JSONObjectToTable(this.read());
    }
}
